/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kylingroup.Desktop.Plugin.FileUploader;

import com.kylingroup.Desktop.Plugin.FileUploader.Bean.Bean_Plugin;
import com.kylingroup.Desktop.Plugin.FileUploader.Utils.PluginWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.RadioButton;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import org.dom4j.Element;

/**
 * FXML Controller class
 *
 * @author kylin
 */
public class DistributeController implements Initializable {
    @FXML
    private TabPane workspace;
    @FXML
    private MenuItem itemload;
    @FXML
    private TextField tname,tclazz,tversion,tauthor,temail;
    @FXML
    private TextArea tdescription;
    @FXML
    private RadioButton ryes,rno;
    @FXML
    private ComboBox ccategory;
    @FXML
    private Button bget,bcreate;
    @FXML
    private Label linfo;
    /**
     * Initializes the controller class.
     */
    private String sname,sautoload,sclazz,scategory,sversion,sauthor,semail,sdescription,sinfo;
    private String fxml;
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        setWorkSpace();
        
        itemload.setOnAction((ActionEvent event) -> {
            System.out.println("fxml:"+fxml);
            try {  
                addTab("test plugin","load the plugin and test",null,loadContent("Fileuploader.fxml"));
            } catch (Exception ex) {
                Logger.getLogger(DistributeController.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
        initUI();
    }
    
    public void setPlugXML(String fxml){
        this.fxml=fxml;
    }
    
    private void setWorkSpace(){
        workspace.setTabClosingPolicy(TabPane.TabClosingPolicy.SELECTED_TAB);
    }
    private void addTab(String title,String tooltip,String imageurl,Node content){
        Tab tab=new Tab();
        
        if(imageurl!=null&&!imageurl.equals("")){
            Image image=new Image(getClass().getResourceAsStream(imageurl));
            ImageView imageView=new ImageView();
            imageView.setImage(image);
            tab.setGraphic(imageView);
        }
        
        tab.setText(title);
        tab.setTooltip(new Tooltip(tooltip));
        tab.setContent(content);
        SingleSelectionModel<Tab> selectionModel=workspace.getSelectionModel();
        selectionModel.select(tab);
        workspace.getTabs().add(tab);
        
    }
    private Node loadContent(String fxml) throws Exception {
        FXMLLoader loader = new FXMLLoader();
        InputStream in = DistributeController.class.getResourceAsStream(fxml);
        loader.setBuilderFactory(new JavaFXBuilderFactory());
        loader.setLocation(DistributeController.class.getResource(fxml));
        loader.setController(new FileuploaderController());
        Node content;
        try {
            content=(Node)loader.load(in);
        } finally {
            in.close();
        }
        
        
        return content;
    }
    private void initUI(){
        
        ToggleGroup group=new ToggleGroup();
        ryes.setToggleGroup(group);
        ryes.setUserData("true");
        rno.setToggleGroup(group);
        rno.setUserData("false");
        group.selectedToggleProperty().addListener(new ChangeListener(){
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                sautoload=group.getSelectedToggle().getUserData().toString();
            }
        });
        
        ArrayList<String> datas=new ArrayList<String>();
        datas.add("tools");
        datas.add("sys");
        ccategory.getItems().addAll(datas);
        SingleSelectionModel cmodel=ccategory.getSelectionModel();
        cmodel.select(0);
        scategory=cmodel.getSelectedItem().toString();
        cmodel.selectedItemProperty().addListener(new ChangeListener(){
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                scategory=cmodel.getSelectedItem().toString();
            }
        });
        
        bget.setOnAction((ActionEvent event)->{
            sclazz=KGPlugFileuploader.class.getName();
            tclazz.setText(sclazz);
        });
        
        bcreate.setOnAction((ActionEvent event)->{
            //name
            sname=tname.getText().trim();
            sversion=tversion.getText().trim();
            sauthor=tauthor.getText().trim();
            semail=temail.getText().trim();
            sdescription=tdescription.getText().trim();
            Bean_Plugin p= new Bean_Plugin();
            p.setName(sname);
            p.setAutoload(Boolean.parseBoolean(sautoload));
            p.setClazz(sclazz);
            p.setCategory(scategory);
            p.setVersion(sversion);
            p.setAuthor(sauthor);
            p.setEmail(semail);
            p.setDescription(sdescription);
            p.setId(1);
            
            linfo.setText("success:"+createXML(p,createZipFolder()+"/plugin.xml"));
        });
    }
    private String createXML(Bean_Plugin p,String path){
        //String path=System.getProperty("user.dir")+"/plugin.xml";
        File xmlfile=new File(path);
        boolean exist=xmlfile.exists();
        PluginWriter writer=new PluginWriter();
        
        if(!exist){
            xmlfile=writer.create(path);
        }
        writer.setXml(xmlfile);
        Element root=writer.getRoot();
        
        writer.addElement(root,p);
        writer.write();
        return xmlfile.getAbsolutePath();
    }
    
    public String createZipFolder(){
        File folder=new File(sname+"-"+sversion);
        if(!folder.exists()){
            folder.mkdir();
        }
        return folder.getAbsolutePath();
    }
}
